// import { getToken } from '@/utils/auth'
import { LsNotifyBox } from '@/utils/msgBox'

const BaseFilter = {
  request: (serverObj) => {
    serverObj.interceptors.request.use(
      (config) => {
        const contentType = config.contentType || 'application/json;charset=UTF-8'
        config.headers['Content-Type'] = contentType
        // if (getToken() != null) {
        //   config.headers.token = getToken() // 发送请求携带最新token
        //   config.headers.Authorization = getToken()
        // }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )
  },
  response: (serverObj) => {
    serverObj.interceptors.response.use((res) => {
      // 如果是附件的下载 只有附件下载的接口返回了content-disposition字段
      if (res.headers['content-disposition']) {
        const data = res.data
        const filename = decodeURIComponent(
          res.headers['content-disposition'].split(';')[1].split('=')[1]
        )
        const fileType = res.headers['content-type'].split(';')[0]
        // 创建一个Blob的实例对象
        const blobStream = new Blob([data], { type: fileType })
        // 通过URL.createObjectURL(blob)创建Blob URL 我们可以像使用Http协议得URL一样使用Blob URL
        const url = window.URL.createObjectURL(blobStream)
        return { url, filename, blobStream }
      }
      const code = res.data.code
      // token过期
      if (code === 401) {
        localStorage.removeItem('TOKEN')
        window.parent.postMessage({ cmd: 'logout' }, '*')
        return res.data
      } else if (code < 200 || code > 300) {
        LsNotifyBox({
          type: 'error',
          message: res.data.msg
        })
        return res.data
      } else {
        return res.data
      }
    })
  }
}

function injectFilter(serverObj) {
  BaseFilter.request(serverObj)
  BaseFilter.response(serverObj)
}

export { injectFilter }
